package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"product/model/mysql"

	"product/goodrpc/goodrpc"
	"product/goodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *goodrpc.UpdateRequest) (*goodrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	var goods mysql.Good
	mysql.DB.Debug().Where("id=?", in.Id).Find(&goods)

	if in.Userid != int64(goods.Userid) {
		return nil, fmt.Errorf("该商品不是此用户的商品,无法修改商品信息")
	}
	var good = mysql.Good{
		Model:    gorm.Model{ID: uint(in.Id)},
		Name:     in.Name,
		Image:    in.Image,
		Quantity: int(in.Quantity),
		Price:    float64(in.Price),
	}
	err := mysql.DB.Debug().Updates(&good).Error
	if err != nil {
		return nil, fmt.Errorf("修改商品失败")
	}
	return &goodrpc.UpdateResponse{Id: int64(good.ID)}, nil
}
